import Vue from 'vue';
import App from './App.vue';
import router from './router';
import ElementUI from 'element-ui';
import VueI18n from 'vue-i18n';
import { messages } from './components/common/i18n';
import 'element-ui/lib/theme-chalk/index.css'; // 默认主题
// import './assets/css/theme-green/index.css'; // 浅绿色主题
import './assets/css/icon.css';
import './components/common/directives';
import 'babel-polyfill';
import axios from 'axios';
import store from './store'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import {download,templateDownload} from '@/utils/xej';

// 全局方法挂载
Vue.prototype.download = download;
Vue.prototype.templateDownload = templateDownload;
Vue.prototype.$axios = axios
Vue.config.productionTip = false;
Vue.use(VueI18n);
Vue.use(ElementUI, {
    size: 'small'
});
const i18n = new VueI18n({
    locale: 'zh',
    messages
});


NProgress.configure({     
    easing: 'ease',  // 动画方式    
    speed: 500,  // 递增进度条的速度    
    showSpinner: false, // 是否显示加载ico    
    trickleSpeed: 200, // 自动递增间隔    
    minimum: 0.3 // 初始化时的最小百分比
})


const whiteList = ['/login'] // 不重定向白名单

//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
    // 每次切换页面时，调用进度条
    NProgress.start();
    const token = localStorage.getItem("token");
   
    if(token){
        if(to.path === '/login'){
            next({path: '/'})
        }else{
            console.log(store.getters.roles);
            // 判断当前用户是否已拉取完userInfo信息
            if(store.getters.roles.length === 0){
            
                // 拉取用户信息
                store.dispatch('GetInfo').then(res=>{
                    const roles = res.data.roles
                   
                    store.dispatch('GenerateRoutes',{roles}).then(accessRoutes => {
                       
                        // 动态添加可访问路由表
                        router.addRoutes(accessRoutes)
                        // hack方法 确保addRoutes已完成
                        next({...to,replace: true})
                    })
                })
        
            }else{
               
                next()
            }
        }
    }else{
        if(whiteList.indexOf(to.path) !== -1){
            next()
        }else{
            next({path: '/login'})
        }
    }
    

});

router.afterEach(() => {  
    // 在即将进入新的页面组件前，关闭掉进度条
    NProgress.done()
})

new Vue({
    router,
    i18n,
    store,
    render: h => h(App)
}).$mount('#app');
